package com.atguigu.lease.web.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import io.minio.credentials.Jwt;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import utils.CodeUtils;
import utils.JwtUtil;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@Service
public class LoginServiceImpl implements LoginService {
    private final SmsService smsService;
    private final StringRedisTemplate stringRedisTemplate;
    private final UserInfoService userInfoService;
    @Override
    public void getcode(String phone) {
        String key= RedisConstant.APP_LOGIN_PREFIX+phone;
        //判断key是否存在即过期，限制发送时间
        Boolean b = stringRedisTemplate.hasKey(key);
        if(Boolean.TRUE.equals(b))
        {
            Long ttl = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            if(RedisConstant.APP_LOGIN_CODE_TTL_SEC-ttl<60)
            {
                throw new LeaseException(504, "验证法发送过于频繁");
            }
        }
        //发送短信
        String randomCode = CodeUtils.getRandomCode(6);
        smsService.sendcode(phone,randomCode);//RedisConstant.APP_LOGIN_CODE_TTL_SEC
        stringRedisTemplate.opsForValue().set(key,randomCode,600, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        System.out.println("begin");
        if(loginVo.getPhone()==null)
        {
            throw new LeaseException(502, "手机号码为空" );
        }
        if(loginVo.getCode()==null)
        {
            throw new LeaseException(503, "验证码为空");
        }
        String key= RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        String value = stringRedisTemplate.opsForValue().get(key);
        //String code = redisTemplate.opsForValue().get(key);
        System.out.println(key+"end");
        System.out.println(value);
        System.out.println("code"+loginVo.getCode());
        System.out.println("phone"+loginVo.getCode());
        if(!loginVo.getCode().equals(value))
        {
            throw new LeaseException(506, "验证码错误");
        }
        else {
            UserInfo userInfo = userInfoService.lambdaQuery()
                    .eq(UserInfo::getPhone, loginVo.getPhone())
                    .one();
            if (userInfo != null) {
                if (userInfo.getStatus().equals(BaseStatus.DISABLE)) {
                    throw new LeaseException(507, "该用户已被禁用");
                }
                else
                        {
                            System.out.println("创建令牌");
                            return JwtUtil.createJwt(userInfo.getId(), loginVo.getPhone());
                        }

            }
            else {
                UserInfo user=new UserInfo();
                user.setPhone(loginVo.getPhone());
                user.setNickname("用户-"+loginVo.getPhone().substring(6));
                user.setStatus(BaseStatus.ENABLE);
                userInfoService.save(user);
                return JwtUtil.createJwt(user.getId(),loginVo.getPhone());
            }
        }
    }

    @Override
    public UserInfoVo getUserInfoById(Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }
}
